import { NameSpace } from 'utils/index';
import { Message } from '@teamix/ui';

import exceed from 'utils/apimap';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;

const ns = NameSpace('pushrules');
export const RECEIVE_PUSHRULES = ns('RECEIVE_PUSHRULES');
export const CREATE_PUSHRULE = ns('CREATE_PUSHRULE');
export const REMOVE_PUSHRULE = ns('REMOVE_PUSHRULE');
export const UPDATE_DATA = ns('UPDATE_DATA');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

// 查询推送规则列表
export function getPushRules() {
  return (dispatch) => {
    updateData({
      isLoadingTable: true,
    })(dispatch);
    exceed
      .forceFetch({
        api: 'projects.push_rule.list',
        params: {
          projectId: pathResource.id,
        },

        data: {
          per_page: 100,
        },
      })
      .then((result) => {
        const newPushRuleData = [];
        result.list.forEach((item) => {
          if (item.ref_type === 'Branch' && item.ref_name) {
            let commitmsgRule = '';
            let emailRule = '';
            const commit_check_rules = [];
            let is_commit_check_enable = false;
            let commit_check_level = '';
            let is_force_push_disable = false;
            let is_prehook_enable = false;
            let prehook_checker_type = '';
            let third_party_url = '';
            item.rule_infos.forEach((rule) => {
              if (rule.checker_name === 'CommitMessageChecker') {
                commitmsgRule = rule.extra_message;
              }
              if (rule.checker_name === 'CommitAuthorEmailChecker') {
                emailRule = rule.extra_message;
              }
              if (rule.checker_name === 'ThirdPartyChecker') {
                is_prehook_enable = true;
                prehook_checker_type = rule.checker_type;
                third_party_url = rule.third_party_url;
              }
              if (['CommitAuthorChecker', 'CommitCommitterChecker'].includes(rule.checker_name)) {
                if (rule.extra_message) {
                  is_commit_check_enable = true;
                  commit_check_level = rule.checker_type;
                  commit_check_rules.push(rule.checker_name);
                }
              }
              if (rule.checker_name === 'ForcePushChecker') {
                is_force_push_disable = !!rule.extra_message;
              }
            });
            newPushRuleData.push({
              id: item.id,
              ref_name: item.ref_name,
              commit_message_checker: commitmsgRule,
              commit_email_checker: emailRule,
              commit_check_rules,
              is_commit_check_enable,
              commit_check_level,
              inherited: item.inherited,
              is_force_push_disable,
              is_prehook_enable,
              third_party_url,
              prehook_checker_type,
            });
          }
        });

        dispatch({
          type: RECEIVE_PUSHRULES,
          data: newPushRuleData,
        });
      });
  };
}

// 新建推送规则
export function create(formData, cb) {
  return (dispatch) => {
    updateData({
      isUpdatingRecord: true,
    })(dispatch);
    exceed
      .fetch({
        api: 'projects.push_rule.create',
        params: {
          projectId: pathResource.id,
        },

        data: formData,
      })
      .then((result) => {
        setTimeout(() => {
          Message.success({
            title: intl.get({
              id: 'code-assets.settingsPushRules.actions.PushRuleCreated',
              defaultMessage: '推送规则新建成功',
            }),
          });
        }, 500);
        dispatch({
          type: CREATE_PUSHRULE,
          data: result,
        });

        updateData({
          isUpdatingRecord: false,
        })(dispatch);
        getPushRules()(dispatch);
        cb && cb();
      })
      .fail(() => {
        updateData({
          isUpdatingRecord: false,
        })(dispatch);
        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };
}

// 删除推送规则
export function remove(ruleId, cb) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'projects.push_rule.delete',
        params: {
          projectId: pathResource.id,
          id: ruleId,
        },
      })
      .then(() => {
        setTimeout(() => {
          Message.success({
            title: intl.get({
              id: 'code-assets.settingsPushRules.actions.PushRuleDeleted',
              defaultMessage: '推送规则删除成功',
            }),
          });
        }, 500);
        dispatch({
          type: REMOVE_PUSHRULE,
          data: ruleId,
        });

        cb && cb();
      });
  };
}

// 根据ID查推送规则
export function getPushRuleById(ruleId, cb) {
  return (dispatch) => {
    updateData({
      isLoadingDialog: true,
    })(dispatch);
    exceed
      .forceFetch({
        api: 'projects.push_rule.get',
        params: {
          projectId: pathResource.id,
          id: ruleId,
        },
      })
      .then((result) => {
        updateData({
          isLoadingDialog: false,
        })(dispatch);
        cb(result);
      });
  };
}

// 编辑推送规则
export function edit(ruleId, formData, cb) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'projects.push_rule.edit',
        params: {
          projectId: pathResource.id,
          id: ruleId,
        },

        data: formData,
      })
      .then(() => {
        setTimeout(() => {
          Message.success({
            title: intl.get({
              id: 'code-assets.settingsPushRules.actions.PushRuleUpdated',
              defaultMessage: '推送规则更新成功',
            }),
          });
        }, 500);
        updateData({
          isUpdatingRecord: false,
        })(dispatch);
        getPushRules()(dispatch);
        cb && cb();
      })
      .fail(() => {
        updateData({
          isUpdatingRecord: false,
        })(dispatch);
        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };
}
